package com.guijianpan.framework.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.guijianpan.framework.constant.Constant;
import com.guijianpan.framework.context.Context;
import com.guijianpan.system.domain.User;

/**
 * 登录拦截器
 * @author yzChen  2015-5-15 10:03:06
 *
 */
public class LoginIntercepter implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		// 判断用户是否已登录
		HttpSession session=request.getSession();
		User user = (User) session.getAttribute(Constant.SESSION_KEY_LOGIN_USER);
		if(null == user) {
			// 跳转到登录页
			response.sendRedirect(request.getContextPath() + "/" + Constant.URL_LOGIN);
			return false;
		}
		
		// 判断该用户是否拥有请求url权限
		String url = request.getRequestURI().replace(request.getContextPath(), "").substring(1);
		if("".equals(url)) {	// 访问根目录
			response.sendRedirect(request.getContextPath() + "/" + Constant.URL_HOME);
			return false;
		}
		if(!Constant.URL_LOGIN.equals(url) && !Constant.URL_LOGINOUT.equals(url)) {	// 不是登录或登出
			if(!user.hasUrlRight(url)) {
				// 跳转到无访问权限页
				response.sendRedirect(request.getContextPath() + "/" + Constant.URL_WITHOUT_RIGHT);
				return false;
			}
		}
		
		// 保存用户信息到线程缓存中
		Context.setCurrentUser(user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object arg2, Exception arg3)
			throws Exception {
		// 判断用户是否已登录
		HttpSession session=request.getSession(); 
		User user = (User) session.getAttribute(Constant.SESSION_KEY_LOGIN_USER);
		if(null == user) {
			// 跳转到登录页
			response.sendRedirect(request.getContextPath() + "/" + Constant.URL_LOGIN);
			return;
		}
		
		// 传递到页面中，展示菜单等
		request.setAttribute("user", user);
	}

}
